package com.nulldev.util.security.encryptAPI.impls.serpent;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class SerpentCipher extends Encryptor {

	private final Serpent sep;
	private final byte[] key;

	public SerpentCipher(final String key) {
		super("encryptapi.tp.serpent", new String[]
			{ "Serpent", "SERPENT", "serpent" }, key);
		this.sep = new Serpent();
		this.sep.setKey(this.key = key.getBytes());
	}

	public SerpentCipher(final byte[] key) {
		super("encryptapi.tp.serpent", new String[]
			{ "Serpent", "SERPENT", "serpent" }, key);
		this.sep = new Serpent();
		this.sep.setKey(this.key = key);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			this.sep.encrypt((byte[]) o);
			return (byte[]) o;
		} else if (o instanceof String) {
			byte[] d = ((String) o).getBytes();
			this.sep.encrypt(d);
			return d;
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			this.sep.encrypt((byte[]) o);
			return Base64.encodeBase64String((byte[]) o);
		} else if (o instanceof String) {
			byte[] d = ((String) o).getBytes();
			this.sep.encrypt(d);
			return Base64.encodeBase64String(d);
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String s) {
		byte[] d = Base64.decodeBase64(s);
		this.sep.decrypt(d);
		return new String(d);
	}

	@Override
	public byte[] decryptToBytes(byte[] b) {
		this.sep.decrypt(b);
		return b;
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return new String(this.key);
	}
}
